package com.xbongbong.paas.script.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.domain.entity.ext.PaasFormDataEntityExt;
import com.xbongbong.paas.domain.entity.ext.PaasFormEntityExt;
import com.xbongbong.paas.enums.PlatFormEnum;
import com.xbongbong.paas.model.PaasFormModel;
import com.xbongbong.paas.pojo.dto.FormDataAddDTO;
import com.xbongbong.paas.pojo.dto.JxcStockDTO;
import com.xbongbong.paas.pojo.dto.UserInfoDTO;
import com.xbongbong.paas.pojo.vo.UserInfoVO;
import com.xbongbong.paas.service.PaasFormDataService;
import com.xbongbong.paas.service.UserService;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.thread.TransmittableThreadLocalUtil;
import com.xbongbong.paas.toolbox.util.DateTimeUtil;
import com.xbongbong.pro.config.ProBaseConfig;
import com.xbongbong.pro.constant.XbbProConstant;
import com.xbongbong.pro.enums.SaasMarkEnum;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.user.pojo.ReturnUserAndDepartmentPojo;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.saas.domain.entity.ContractProductEntity;
import com.xbongbong.saas.domain.entity.PurchaseProductEntity;
import com.xbongbong.saas.domain.entity.ext.WarehouseEntityExt;
import com.xbongbong.saas.enums.InstockTypeEnum;
import com.xbongbong.saas.enums.OutstockTypeEnum;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.business.ContractEnum;
import com.xbongbong.saas.enums.business.ContractOutstockEnum;
import com.xbongbong.saas.enums.business.InstockEnum;
import com.xbongbong.saas.enums.business.OutstockEnum;
import com.xbongbong.saas.enums.business.PurchaseEnum;
import com.xbongbong.saas.enums.business.PurchaseInstockEnum;
import com.xbongbong.saas.enums.business.WarehouseEnum;
import com.xbongbong.saas.model.ContractModel;
import com.xbongbong.saas.model.ContractProductModel;
import com.xbongbong.saas.model.PurchaseModel;
import com.xbongbong.saas.model.PurchaseProductModel;
import com.xbongbong.saas.model.WarehouseModel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.MediaType;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

@RestController
@RequestMapping(XbbProConstant.API_ROOT_PREFIX+"/script/preApproval")
public class PreApprovalScriptController {
    private static final Logger LOG = LoggerFactory.getLogger(PreApprovalScriptController.class);
    @Resource
    private ProBaseConfig proBaseConfig;
    @Resource
    private PaasFormDataService paasFormDataService;
    @Resource
    private PaasFormModel paasFormModel;
    @Resource
    private UserService userService;
    @Resource
    private WarehouseModel warehouseModel;
    @Resource
    private ContractModel contractModel;
    @Resource
    private PurchaseModel purchaseModel;
    @Resource
    private ContractProductModel contractProductModel;
    @Resource
    private PurchaseProductModel purchaseProductModel;

    @RequestMapping(value = "/addSheet", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String addStock(@RequestBody @Valid JxcStockDTO jxcStockDTO, BindingResult br) throws Exception {
        if (!proBaseConfig.getXbbCode().equals(jxcStockDTO.getXbbCode())) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100006, SystemErrorCodeEnum.API_ERROR_100006.getMsg());
        }
        Integer businessType = jxcStockDTO.getBusinessType();
        String corpid = jxcStockDTO.getCorpid();
        int size = jxcStockDTO.getSize() == null ? 10000 : jxcStockDTO.getSize();
        if (!Objects.equals(businessType,XbbRefTypeEnum.PURCHASE_INSTOCK.getCode()) && !Objects.equals(businessType,XbbRefTypeEnum.CONTRACT_OUTSTOCK.getCode())){
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001,"只允许销售出库和采购入库");
        }
        boolean isContract = Objects.equals(businessType,XbbRefTypeEnum.CONTRACT_OUTSTOCK.getCode());
        Long refId = jxcStockDTO.getRefId();
        PaasFormDataEntityExt paasFormDataEntityExt;
        Map<Long, Long> refProductIdMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        if (isContract) {
            paasFormDataEntityExt = contractModel.getByKey(refId, corpid);
            List<ContractProductEntity> contractProductList = contractProductModel.getProductsByConId(refId, corpid);
            if (Objects.isNull(paasFormDataEntityExt) || contractProductList.isEmpty()) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001,"销售合同不存在");
            }

            contractProductList.forEach(item -> refProductIdMap.put(item.getId(), item.getProductId()));
        } else {
            paasFormDataEntityExt = purchaseModel.getByKey(refId, corpid);
            List<PurchaseProductEntity> purchaseProductList = purchaseProductModel.getProductsByPurchaseId(corpid, refId);
            if (Objects.isNull(paasFormDataEntityExt) || purchaseProductList.isEmpty()) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001,"采购合同不存在");
            }
            purchaseProductList.forEach(item -> refProductIdMap.put(item.getId(), item.getProductId()));
        }
        WarehouseEntityExt warehouseEntityExt = warehouseModel.getByKey(jxcStockDTO.getWarehouseId(),corpid);
        if (Objects.isNull(warehouseEntityExt)) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001,"仓库不存在");
        }
        // 基础数据封装
        FormDataAddDTO formDataAddDTO = new FormDataAddDTO();
        formDataAddDTO.setCorpid(jxcStockDTO.getCorpid());
        formDataAddDTO.setUserId(jxcStockDTO.getUserId());
        formDataAddDTO.setPlatform(StringConstant.PLATFORM_WEB);
        formDataAddDTO.setSaasMark(SaasMarkEnum.SAAS.getCode());
        PaasFormEntityExt paasFormEntityExt = paasFormModel.getByBusinessType(businessType, corpid);
        formDataAddDTO.setAppId(paasFormEntityExt.getAppId());
        formDataAddDTO.setMenuId(paasFormEntityExt.getMenuId());
        formDataAddDTO.setFormId(paasFormEntityExt.getId());
        formDataAddDTO.setBusinessType(businessType);
        formDataAddDTO.setSubBusinessType(businessType);
        List<ReturnUserAndDepartmentPojo> ownerIdList = new ArrayList<>();
        ReturnUserAndDepartmentPojo ownerId = new ReturnUserAndDepartmentPojo();
        ownerId.setId(jxcStockDTO.getUserId());
        ownerId.setName("李杰");
        ownerIdList.add(ownerId);
        formDataAddDTO.setOwnerId(ownerIdList);
        //userVO
        UserInfoDTO userInfoDTO = new UserInfoDTO();
        userInfoDTO.setCorpid(corpid);
        userInfoDTO.setUserId(jxcStockDTO.getUserId());
        userInfoDTO.setPlatform(PlatFormEnum.INTERNAL.getValue());
        userInfoDTO.setPaasPermissionsFlag(true);
        userInfoDTO.setUserDetailFlag(true);
        userInfoDTO.setCompanyInfoFlag(false);
        UserInfoVO userInfoResp = userService.getUserInfo(userInfoDTO);
        formDataAddDTO.setLoginUser(userInfoResp.getUser());
        // 关联单据
        JSONArray refArray = new JSONArray();
        JSONObject refObject = new JSONObject();
        refObject.put("id",refId);
        refObject.put("name", paasFormDataEntityExt.getSerialNo());
        refArray.add(refObject);
        // 关联仓库
        JSONArray warehouseArray = new JSONArray();
        JSONObject warehouseObject = new JSONObject();
        warehouseObject.put("id",warehouseEntityExt.getId());
        warehouseObject.put("name", warehouseEntityExt.getData().getString(WarehouseEnum.WAREHOUSE_NAME.getAttr()));
        warehouseArray.add(warehouseObject);
        // 关联客户或供应商
        JSONArray linkJsonArray = new JSONArray();
        JSONObject linkJsonObject = new JSONObject();
        linkJsonArray.add(linkJsonObject);
        if (isContract) {
            linkJsonObject.put("id",paasFormDataEntityExt.getData().get(ContractEnum.LINK_CUSTOMER.getAttr()));
            linkJsonObject.put("name", paasFormDataEntityExt.getData().get(ContractEnum.LINK_CUSTOMER_HIDE.getAttr()));
        } else {
            linkJsonObject.put("id",paasFormDataEntityExt.getData().get(PurchaseEnum.SUPPLIER_ID.getAttr()));
            linkJsonObject.put("name", paasFormDataEntityExt.getData().get(PurchaseEnum.SUPPLIER_ID_LINKED_TEXT.getAttr()));
        }
        // 基础
        Long todayInt = DateTimeUtil.getTodayInt();
        Long serialNo = DateTimeUtil.getInt();
        String preFixSerialNo = isContract ? "XSCK.SCRIPT" : "CGRK.SCRIPT" ;
        String formDataAddStr = JSON.toJSONString(formDataAddDTO);
        TransmittableThreadLocalUtil.setValue(formDataAddDTO.getSaasMark(), formDataAddDTO.getBusinessType(), formDataAddDTO.getMenuId(), formDataAddDTO.getDistributorMark());
        for (int i = 0; i < size; i++) {
            FormDataAddDTO formDataAdd = JSON.toJavaObject(JSON.parseObject(formDataAddStr), FormDataAddDTO.class);
            String serialNoStr = preFixSerialNo + serialNo;
            formDataAdd.setSerialNo(serialNoStr);
            JSONObject data = new JSONObject();
            data.put("serialNo",serialNoStr);
            JSONArray productArray = new JSONArray();
            refProductIdMap.forEach((key, value) -> {
                JSONObject product = new JSONObject();
                JSONObject text_1 = new JSONObject();
                text_1.put("dataId",value);
                text_1.put("id",key);
                product.put("text_1",text_1);
                product.put("text_6",warehouseArray);
                product.put("num_3",1);
                product.put("num_2",1);
                product.put("num_7",1);
                product.put("refProductId", key);
                product.put("productSubId", 0);
                if (isContract) {
                    product.put("num_6", 1);
                    product.put("num_5", 1);
                }
                productArray.add(product);
            });
            data.put("array_1",productArray);
            data.put("date_1",todayInt);
            data.put("ownerId",ownerIdList);
            if (isContract){
                data.put(ContractOutstockEnum.REF_ID.getAttr(), refArray);
                data.put(OutstockEnum.TYPE.getAttr(), OutstockTypeEnum.CONTRACT_OUTSTOCK.getCode());
                data.put(ContractOutstockEnum.LINK_CUSTOMER.getAttr(), linkJsonArray);
            }else {
                data.put(PurchaseInstockEnum.REF_ID.getAttr(), refArray);
                data.put(InstockEnum.TYPE.getAttr(), InstockTypeEnum.PURCHASE_INSTOCK.getCode());
                data.put(PurchaseInstockEnum.SUPPLIER_ID.getAttr(), linkJsonArray);
            }
            data.put("text_2",warehouseArray);
            formDataAdd.setDataList(data);
            try {
                paasFormDataService.add(formDataAdd);
            } catch (Exception e) {
                LOG.warn("", e);
            }
            serialNo++;
            LOG.warn("======已完成" + (i + 1) + "/" + size +"条");
        }
        return "success";
    }
}
